package main

import (
	"encoding/json"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"io/ioutil"
	"os"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	_ "peilian-api/bootstrap"
)

func InitMySQL() (*gorm.DB, error) {
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s",
		variable.Config.Mysql.UserName,
		variable.Config.Mysql.PassWord,
		variable.Config.Mysql.Host,
		variable.Config.Mysql.Port,
		variable.Config.Mysql.DBName,
		variable.Config.Mysql.TimeOut,
	)
	DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		return nil, err
	}
	sqlDB, _ := DB.DB()
	//设置数据库连接池参数
	sqlDB.SetMaxOpenConns(100) //设置数据库连接池最大连接数
	sqlDB.SetMaxIdleConns(20)  //连接池最大允许的空闲连接数，如果没有sql任务需要执行的连接数大于20，超过的连接会被连接池关闭。
	return DB, nil
}

func ReadFileToMap(path string) []map[string]string {
	jsonFile, err := os.Open(path)
	if err != nil {
		fmt.Println("error opening json file: " + err.Error())
		return nil
	}
	jsonData, err := ioutil.ReadAll(jsonFile)
	if err != nil {
		fmt.Println("error reading json file :" + err.Error())
		return nil
	}
	result := make([]map[string]string, 0)
	err = json.Unmarshal(jsonData, &result)
	if err != nil {
		fmt.Println("error unmarshal json file: " + err.Error())
	}
	return result
}

func ImportNormalQues(db *gorm.DB) {
	questions := ReadFileToMap("scripts/import_data/标准问&追问_v2.json")
	if questions == nil {
		return
	}
	for _, member := range questions {
		career := new(tables.Career)
		if err := db.Where(&tables.Career{Name: member["category"]}).FirstOrCreate(&career).Error; err != nil {
			fmt.Println(err.Error())
			return
		}
		question := new(tables.Question)
		question.Criteria = member["tags"]
		question.Text = member["questionText"]
		question.Video = member["video"]
		question.CareerID = career.ID
		question.ParentText = member["parentQuestionText"]
		if question.ParentText == "" {
			question.Type = "normal_question"
		} else {
			question.Type = "extra_question"
		}
		db.Where(&tables.Question{Text: question.Text}).FirstOrCreate(&question)
	}
}

func ImportMarginVideo(db *gorm.DB) {
	convertVideos := ReadFileToMap("scripts/import_data/转场_v2.json")
	if convertVideos == nil {
		return
	}
	for _, member := range convertVideos {
		video := new(tables.MarginVideo)
		video.Text = member["questionText"]
		video.Video = member["video"]
		video.Type = "convert"
		video.Tag = member["tag"]
		db.Where(&tables.MarginVideo{Text: video.Text}).FirstOrCreate(&video)
	}

	confirmVideos := ReadFileToMap("scripts/import_data/非问题视频_v2.json")
	if confirmVideos == nil {
		return
	}
	for i, v := range confirmVideos {
		video := new(tables.MarginVideo)
		if i < 3 {
			video.Type = "polar"
		} else if i == 3 {
			video.Type = "init"
		} else if i == 4 {
			video.Type = "finish"
		} else {
			video.Type = "default"
		}

		video.Text = v["questionText"]
		video.Video = v["video"]
		db.Where(&tables.MarginVideo{Text: video.Text}).FirstOrCreate(&video)
	}
}

func main() {
	db, _ := InitMySQL()
	fmt.Println(db)
	ImportNormalQues(db)
	ImportMarginVideo(db)
}
